<?php
/**
 * @category   Ac
 * @package    Application_Model
 * @copyright  Orient Network Ltd
 * @license    Closed
 * @author     Olivier Bregeras
 */
class Model_Message extends Ac_Model
{
	const STATUS_SENT = 1;
	const STATUS_PENDING = 2;
    const STATUS_SPAM = 3;
    private $mail;
    protected static  $_collection = 'message';
    public $force_send;
    public $params;
    public $files;

    /**
     *
     * @var array define the requirements for this model
     */
    protected static $_requirements = array(
        'fo'  => array('Array'), //From
    );

    protected static $_transcript = array(
        '_id'  => '_id',
        'su'   => 'subject',
        'ct'   => 'message',
        'c_dt' => 'created_at',
        'to'   => 'to',
        'fo'   => 'from',
        'tp'   => 'template',
        'ob'   => 'object',
        //'pr'   => 'params'
    );


    public function __construct($data = array(), $config = array())
	{
        $config['collection'] = 'message';
        self::ensureIndex(array('_type' => 1));
		
        parent::__construct($data, $config);
    }


    public function __set($name, $arguments)
    {
        if ($name == 'message') {
            $this->message_txt = $arguments;
        } else {
            return parent::__set($name, $arguments);
        }
    }

    function sendMessage($force_send = false) {
		//var_dump($this->params['listing']->tl_en);exit();
        $this->mail = new Ac_Mail();
		$temp = $this->subject;
		if(!empty($this->params['listing']->tl_en)){
			$this->subject = "[".$this->params['listing']->tl_en."]";
		}
		
        $this->save();
        
        $this->subject = $temp;
        /*
        $this->mail->setSubject($this->su);

        // on spécifie le titre qu'on affichera dans le layout
        

        // on spécifie les scripts à utiliser pour la vue
        $this->mail->setScriptText($this->tp.'.text', $this->ob);
        //$this->mail->setScriptHtml($this->tp.'.html', $this->ob);

        // on envoi le tout au webmaster
        //$mail->setFrom($config->mail->webmaster, 'Webmaster');
        //$this->mail->setFromConfig(AC_Mail::WEBMASTER);
        if (!empty($this->from)) {
            $this->mail->setFrom($this->from);
        } else {
            $this->mail->setFrom($this->mail->getConfig()->webmaster->address, $this->mail->getConfig()->webmaster->name);
        }

        //TODO: change before launch
        //$this->mail->setTo($this->to);
        $this->mail->setTo('asiaclassified1@gmail.com');
        $this->mail->send();
         *
         */
        
        //find the language of the recipient
        if ($user = Model_User::one(array('email' => $this->to))) {
            $language = $user->language;
        }
        
        if (empty($language)) {
            $language = Zend_Registry::get('current_language');
        }
        
        
        
        $view = $this->mail->getView();
        $lang_bak = $view->current_language;
        
        $translate = Zend_Registry::get('translate');
        $loc = Model_Translate::EN;
        if ($language == 'tc') {
            $loc = Model_Translate::TC;
        } elseif ($language == 'sc') {
            $loc = Model_Translate::SC;
        } elseif ($language == 'jp') {
            $loc = Model_Translate::JP;
        }

        $translate->setLocale($loc);        
        
        
        $this->mail->setSubject($this->subject);

        // on spécifie le titre qu'on affichera dans le layout
        //$mail->title = $view->t($message);

        $view->message_txt = $this->message_txt;
        // on spécifie les scripts à utiliser pour la vue
        if ($this->template === Ac_Mail::TEMPLATE_NEWUSER) {
            $view->user = $this->params['user'];
            // $this->mail->setScriptText('new-user.text', 'user');
            $this->mail->setScriptHtml('new-user.html', 'user');
        } elseif ($this->template === Ac_Mail::TEMPLATE_SENDMESSAGE_POSTER) {
        	//save message first..status pendeing
        //queue for 1min..
        //if the there are 10msg under 1min,
        //change the status to spam
        
            $view->listing = $this->params['listing'];
            $view->email_sender = $this->params['email_sender'];
            $view->phone_number = $this->params['phone_number'];
            if (!empty($this->params['user'])) {
                $view->user = $this->params['user'];
                $view->password = $this->params['password'];
            }
            // $this->mail->setScriptText('send-message-poster.text', 'listing');
            $this->mail->setScriptHtml('send-message-poster.html', 'listing');
        } elseif ($this->template === Ac_Mail::TEMPLATE_SENDMESSAGE_SENDER) {
            $view->listing = $this->params['listing'];
			
			if (!empty($this->params['username'])) {
				 $view->username = $this->params['username'];
			}
            if (!empty($this->params['user'])) {
                $view->user = $this->params['user'];
                $view->password = $this->params['password'];
            }
            // $this->mail->setScriptText('send-message-sender.text', 'listing');
            $this->mail->setScriptHtml('send-message-sender.html', 'listing');
        } elseif ($this->template === Ac_Mail::TEMPLATE_NEWUSER_POSTANAD) {
            $view->listing = $this->params['listing'];
            $view->user = $this->params['user'];
            // $this->mail->setScriptText('new-user-postanad.text', 'user');
            $this->mail->setScriptHtml('new-user-postanad.html', 'user');
        } elseif ($this->template === Ac_Mail::TEMPLATE_FORGOTPASSWORD) {
            $view->password = $this->params['password'];
            $view->user = $this->params['user'];
            $this->mail->setScriptText('forgot-password.text', 'user');
        } elseif ($this->template === Ac_Mail::TEMPLATE_CAMPAIGN_SAMSUNG) {
            $view->password = $this->params['password'];
            $view->user = $this->params['user'];
            $this->mail->setScriptText('samsung.text', 'campaign');
        } elseif ($this->template === Ac_Mail::TEMPLATE_ACCOUNT_UPGRADE) {
			$view->username = $this->params['user'];
			$view->link = $this->params['link'];
			$view->company_name = $this->params['company_name'];
            $this->mail->setScriptHtml('upgrade-user.html', 'user');
        } elseif ($this->template === Ac_Mail::TEMPLATE_CAMPAIGN_BULKLISTING) {
			$view->name = $this->params['name'];
			$view->tel 	= $this->params['tel'];
			$view->email = $this->params['email'];
			$view->url	 = $this->params['url'];
			//'contact_name' => $contact_name, 'tel_num' => $tel_num, 'email_add' => $email_add, 'website' => $website, 'language' => $language
            $this->mail->setScriptHtml('bulklisting.text', 'campaign');
        } elseif ($this->template === Ac_Mail::TEMPLATE_SPAM_ALERT) {
			$view->email_add = $this->params['email_add'];
			//'contact_name' => $contact_name, 'tel_num' => $tel_num, 'email_add' => $email_add, 'website' => $website, 'language' => $language
            $this->mail->setScriptHtml('spamalert.text', 'listing');
        }elseif($this->template === Ac_Mail::TEMPLATE_SIMILAR_LIST) {
        	$view->listings = $this->params['listings'];
            $view->user = $this->params['user'];
        	$this->mail->setScriptHtml('send-similar-listings.html', 'listing');
        }
        
        //attach files if they exists.
        if (!empty($this->files)) {
            $finfo = new finfo(FILEINFO_MIME, '/usr/share/misc/magic');
            foreach((array) $this->files as $file) {
                //test file type
                $mime = $finfo->file($file);
                $mime = explode('; ',$mime);
                $mime_type = '';
                if ($mime[0] == 'application/zip') {
                    if (substr($file, -4) == 'docx') {
                        $mime_type = 'application/msword';
                    }
                } else if ($mime[0] == 'application/octet-stream' ) {
                    if (substr($file, -3) != 'odt') {
                        $mime_type = 'application/vnd.oasis.opendocument.text';
                    }
                } else if (!in_array($mime[0], array('text/plain', 'application/pdf', 'application/msword'))) {
                     $mime_type = $mime[0];
                }
                $this->mail->createAttachment(file_get_contents($file), $mime_type,Zend_Mime::DISPOSITION_ATTACHMENT, Zend_Mime::ENCODING_BASE64, basename($file));
            }
        }
        
        
        // on envoi le tout au webmaster
        //$mail->setFrom($config->mail->webmaster, 'Webmaster');
        if ($this->from === Ac_Mail::WEBMASTER) {
            $conf = $this->mail->getConfig();
            $sender_email = $conf->webmaster->address;
            $sender_name  = $conf->webmaster->name;
        } else {
            $sender_email = $this->from->email;
            if (!empty($this->from->name)) {
                $sender_name  = $this->from->name;
            } else {
                $sender_name = '';
            }
        }
        $this->mail->setFrom($sender_email, $sender_name);

        if (is_string($this->to)) {
            $this->mail->clearRecipients();
            //$this->mail->setTo('asiaclassified1@gmail.com');
            $this->mail->setTo($this->to);
            if ($force_send) {
                //var_dump($this->mail);exit;
                $this->mail->send();
            }else {
                //TODO:include it in queue to be send out
            }

        } elseif (is_array($this->to)) {
            foreach ($this->to as $name => $add) {
                $this->mail->clearRecipients();
                $this->mail->setTo($add, $name);
                //$this->mail->setTo('asiaclassified1@gmail.com');
                if ($force_send) {
                    //var_dump($this->mail);exit;
                    $this->mail->send();
                } else {
                    //TODO:include it in queue to be send out
                }
                //unset($mail2);
            }
        }
        
        $language = $lang_bak;
        $loc = Model_Translate::EN;
        if ($language == 'tc') {
            $loc = Model_Translate::TC;
        } elseif ($language == 'sc') {
            $loc = Model_Translate::SC;
        } elseif ($language == 'jp') {
            $loc = Model_Translate::JP;
        }

        $translate->setLocale($loc);        
    }
}